<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\shop\controller\admin;

use app\admin\common\AdminController;

class Goods extends AdminController
{
    public function index()
    {
        $pagination = $this->_get_pagination_data();

        $pagination['rows_count'] = model('shop/goods')
            ->where($pagination['where_map'])->count();

        $pagination['total_pages'] = ceil($pagination['rows_count'] / $pagination['page_size']);
        $pagination['page_num'] = $pagination['page_num'] > $pagination['total_pages'] ? 1 : $pagination['page_num'];

        $goods_list = model('shop/goods')
            ->where($pagination['where_map'])
            ->page($pagination['page_num'], $pagination['page_size'])
            ->order($pagination['sort_field'], $pagination['sort_order'])
            ->select();

        $this->assign('goods_list', $goods_list);
        $this->assign('pagination', $pagination);
        $this->display('admin/goods/goods_list');
    }

    public function create()
    {
        $goods_info = model('shop/goods')->initDefault();

        if (request()->isPost()) {
            $goods_info->acceptData($this->post_array());

            if ($goods_info->save() !== false) {
                $this->success('新增成功。', $this->url('index'));
            }
        }

        $this->assign('goods_info', $goods_info);
        $this->display('admin/goods/goods_form');
    }

    public function modify($id)
    {
        $goods_info = model('shop/goods')->findOrFail($id);

        if (request()->isPost()) {
            $goods_info->acceptData($this->post_array());

            if ($goods_info->save() !== false) {
                $this->success('修改成功。', $this->url('index'));
            }
        }

        $this->assign('goods_info', $goods_info);
        $this->display('admin/goods/goods_form');
    }

    public function bulk_delete($ids = array())
    {
        $goods_list = model('shop/goods')->where('id', 'in', $ids)->select();

        foreach ($goods_list as $goods_info) {
            $goods_info->delete();
        }

        $this->success('删除成功。', $this->url('index'));
    }
}